package com.originskyseed.platform.job.jobhandler.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.job.biz.model.ReturnT;
import com.originskyseed.platform.core.job.handler.IJobHandler;
import com.originskyseed.platform.core.job.handler.annotation.JobHandler;
import com.originskyseed.platform.core.job.log.JobLogger;
import com.originskyseed.platform.task.model.Task;
import com.originskyseed.platform.task.model.TaskRelateAssignPerson;
import com.originskyseed.platform.task.service.ITaskRelateAssignPersonService;
import com.originskyseed.platform.task.service.ITaskService;
import com.originskyseed.platform.user.model.SpreadPlayerLimit;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.ISpreadPlayerLimitService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 定时修改逾期的任务状态、主播玩家推广上限记录
 *
 * @Author: wlj @date: 2021/4/20
 */

@Component
@JobHandler(value = "taskJobHandler")
public class TaskJobHandler extends IJobHandler {

	@DubboReference
	private ITaskService taskService;

	@DubboReference
	private ITaskRelateAssignPersonService taskRelateAssignPersonService;

	@DubboReference
	private ISpreadPlayerLimitService spreadPlayerLimitService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IPlayerService playerService;

	@Override
	public ReturnT<String> execute(String tenantCode) throws Exception {
		try {
			TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
			taskRelateAssignPerson.setState(1);// 未完成
			List<TaskRelateAssignPerson> taskRelateAssignPersonList = this.taskRelateAssignPersonService.selectList(taskRelateAssignPerson, tenantCode);
			Date startTime = new Date();
			if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
				for (int i = 0; i < taskRelateAssignPersonList.size(); i++) {
					TaskRelateAssignPerson relateAssignPerson = taskRelateAssignPersonList.get(i);
					Task task = taskService.selectByPrimaryKeyTenantCode(relateAssignPerson.getTaskId(), tenantCode);
					if (task != null && task.getEndTime() != null) {
						Date endTime = task.getEndTime();
						if (startTime.getTime() > endTime.getTime()) {
							relateAssignPerson.setState(3);// 逾期
							this.taskRelateAssignPersonService.updateByPrimaryKeySelectiveTenantCode(relateAssignPerson, tenantCode);
						}
					}
				}
			}

			taskRelateAssignPerson.setState(0);// 未开始
			List<TaskRelateAssignPerson> taskRelateAssignPersonList1 = this.taskRelateAssignPersonService.selectList(taskRelateAssignPerson, tenantCode);
			if (taskRelateAssignPersonList1 != null && taskRelateAssignPersonList1.size() > 0) {
				for (int i = 0; i < taskRelateAssignPersonList1.size(); i++) {
					TaskRelateAssignPerson relateAssignPerson = taskRelateAssignPersonList1.get(i);
					Task task = taskService.selectByPrimaryKeyTenantCode(relateAssignPerson.getTaskId(), tenantCode);
					if (task != null && task.getBeginTime() != null && task.getEndTime() != null) {
						Date endTime = task.getEndTime();
						Date beginTime = task.getBeginTime();
						if (startTime.getTime() > endTime.getTime()) {
							relateAssignPerson.setState(3);// 逾期
						} else if (startTime.getTime() > beginTime.getTime() && startTime.getTime() < endTime.getTime()) {
							relateAssignPerson.setState(1);// 未完成
						}
						this.taskRelateAssignPersonService.updateByPrimaryKeySelectiveTenantCode(relateAssignPerson, tenantCode);
					}
				}
			}

			//玩家主播上限记录触发任务完成
			List<Task> taskList = this.taskService.selectPromoteTaskJobListTenantCode(1, tenantCode);//未完成
			if(taskList != null && taskList.size() > 0){
				for (Task task : taskList) {
					//查询那些业务员接抢单了
					List<TaskRelateAssignPerson> relateAssignPersonList = this.taskRelateAssignPersonService.selectListByTaskIdTenantCode(task.getId(),tenantCode);
					if(relateAssignPersonList != null && relateAssignPersonList.size() > 0){
						//业务员id
						List<String> list = new ArrayList<>();
						for (TaskRelateAssignPerson relateAssignPerson : relateAssignPersonList) {
							if(relateAssignPerson.getUserId()  != null && StringUtils.isNotEmpty(relateAssignPerson.getUserId())){
								UserInfo userInfo = this.userInfoService.selectByPrimaryKeyTenantCode(relateAssignPerson.getUserId(), tenantCode);
								if(userInfo != null && userInfo.getOtherAccount() != null && StringUtils.isNotEmpty(userInfo.getOtherAccount())){
									list.add(userInfo.getOtherAccount());
								}
							}
						}
						if(list != null && list.size() > 0) {
							//主播id
							String anchorId = task.getOtherAccount();
							//查询主播设置的上限
							if (task.getAnchorId() != null && StringUtils.isNotEmpty(task.getAnchorId())) {
								SpreadPlayerLimit spreadPlayerLimit = this.spreadPlayerLimitService.selectByObjIdTenantCode(task.getAnchorId(), tenantCode);
								if (spreadPlayerLimit == null) {
									spreadPlayerLimit = this.spreadPlayerLimitService.selectByObjIdTenantCode("-1", tenantCode);
								}
								if (spreadPlayerLimit != null) {
									if (spreadPlayerLimit.getNum() != null && spreadPlayerLimit.getNum() > 0) {
										int limitNum = spreadPlayerLimit.getNum();
										//统计个数
										Map<String, Object> map = new HashMap<>();
										map.put("anchorId", anchorId);
										map.put("list", list);
										int playerNum = this.playerService.countTaskAnchorNumTenantCode(map, tenantCode);
										//任务完成
										if (playerNum >= limitNum) {
											task.setState(2);
											this.taskService.updateByPrimaryKeySelectiveTenantCode(task, tenantCode);
											this.taskRelateAssignPersonService.updateFinishTaskByTaskIdTenantCode(task.getId(), tenantCode);
										}
									}
								}
							}
						}
					}
				}
			}

		} catch (Exception e) {
			JobLogger.log("任务广场：" + getExceptionDetail(e));
			return FAIL;
		}
		return SUCCESS;
	}

	/**
	 * 获取异常详细信息，知道出了什么错，错在哪个类的第几行 .
	 *
	 * @param ex
	 * @return
	 */
	public static String getExceptionDetail(Exception ex) {
		String ret = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PrintStream pout = new PrintStream(out);
		try {
			ex.printStackTrace(pout);
			ret = new String(out.toByteArray());
		} catch (Exception e) {
		} finally {
			try {
				pout.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

}
